package com.atguigu.teach.juc;

import java.util.concurrent.*;

/**
 * @auther zzyy
 * @create 2020-03-30 14:15
 */
public class MyThreadPoolDemo
{
    public static void main(String[] args)
    {
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        try
        {
            //有20个请求线程来该银行办理业务，目前有5个工作人员对外提供服务。
            for (int i = 1; i <=8; i++) {
                int finalI = i;
                threadPool.submit(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t"+"为顾客："+ finalI +" 办理业务");
                    //暂停几秒钟线程
                    try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }

    public static void initPool()
    {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池5线程,一个银行里面有5个工作人员办理业务
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1线程,一个银行里面有1个工作人员办理业务
        //ExecutorService threadPool = Executors.newCachedThreadPool();//一池N线程,一个银行里面有N个工作人员办理业务

        try
        {
            //有20个请求线程来该银行办理业务，目前有5个工作人员对外提供服务。
            for (int i = 1; i <=20; i++) {
                int finalI = i;
                threadPool.submit(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t"+"为顾客："+ finalI +" 办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}
